package com.sesample.seandroidsample;

import java.util.ArrayList;

import android.content.Context;

public class Cart {

  /**
   * An Item(number, productId) represents a single product and amount in the cart
   */
  public class Item {
    private int mNumber;
    private int mProductId;

    public Item(int number, int productId) {
      mNumber = number;
      mProductId = productId;
    }
    public int getNumber() {
      return mNumber;
    }
    public int getProductId() {
      return mProductId;
    }
    public void setNumber(int number) {
      mNumber = number;
    }
    public void setProductId(int productId) {
      mProductId = productId;
    }
  }

  private static Cart sInstance;
  public static Cart getInstance(Context appContext) {
    if (null == sInstance) {
      // Initializing the cart contents
      sInstance = new Cart(appContext);
    }
    return sInstance;
  }

  private final Context mAppContext;

  private final ArrayList<Item> mItems;

  public Cart(Context appContext) {
    // Initialize the cart based on the user identity etc
    mItems = new ArrayList<Item>();
    mAppContext = appContext;
  }

  public int addToCart(int number, int productId) {
    if (0 >= number) {
      return 0;
    }

    boolean isNewItem = true;
    for (int i=0; i<mItems.size(); i++) {
      Item item = mItems.get(i);
      if (productId == item.getProductId()) {
        // Already in cart, simply increase the number
        int newNumber = item.getNumber() + number;
        item.setNumber(newNumber);
        isNewItem = false;
      }
    }
    if (isNewItem) {
      Item item = new Item(number, productId);
      mItems.add(item);
    }
    return number;
  }

  /**
   * Get the total price for the items in cart
   * @return
   */
  public float calcTotalPrice() {
    float totalPrice = 0;
    Catalogue inventory = Catalogue.getInstance(mAppContext);
    for (int i=0; i<mItems.size(); i++) {
      Item item = mItems.get(i);
      totalPrice += inventory.getProductById(item.getProductId()).getPrice() * item.getNumber();
    }
    return totalPrice;
  }

  public void clearCart() {
    mItems.clear();
  }

  public ArrayList<Item> getItems() {
    return mItems;
  }

  public int getNumberByProductId(int id) {
    for (int i=0; i<mItems.size(); i++) {
      Item item = mItems.get(i);
      if (id == item.getProductId()) {
        return item.getNumber();
      }
    }
    return 0;
  }

  public boolean isEmpty() {
    return 0 == mItems.size();
  }

  /**
   * Remove product from the cart
   * @param id Product ID
   * @return Number of items removed
   */
  public int removeByProductId(int id) {
    for (int i=0; i<mItems.size(); i++) {
      Item item = mItems.get(i);
      if (id == item.getProductId()) {
        int numToRemove = item.getNumber();
        mItems.remove(i);
        return numToRemove;
      }
    }
    return 0;
  }
}
